# coding=utf-8
import serial
import threading
import serial.tools.list_ports
from dianbiao_serial_protocol import *
import dianbiao_logic


def serial_get_all_port():
    port_list=[]
    ports = serial.tools.list_ports.comports()
    for p in ports:
        port_list.append(p.device)
    return port_list

class serial_one_port_object():
    def __init__(self, port_tmp, baudrate_tmp):
        try:
            self.serial_port=serial.Serial(port=port_tmp,baudrate=baudrate_tmp,parity='E',timeout=0.5)
            self.serial_port.flush()       #等待所有数据写出。
            self.serial_port.flushInput()  #丢弃接收缓存中的所有数据
        except:
            self.serial_port=None

    def check_serial_port(self):
        return self.serial_port

    def check_serial_port_close(self):
        try:
            if(self.serial_port==None):
                pass
            else:
                self.serial_port.close()
        except:
            pass

    def hextostr(self,list):
        if(type(list)==type([])):
            hexstr = ""
            for item in list:
                temp = hex(item)
                if (len(temp) == 3):
                    hexstr = hexstr + "0" + temp[2]
                else:
                    hexstr = hexstr + temp[2] + temp[3]
            strsend = hexstr.decode("hex")
            return strsend
        return ""

    def serial_data_read(self):
        list_tmp = []
        # 找68H头码
        data_chr_tmp=self.serial_port.read(1)
        if(len(data_chr_tmp)):
            data_tmp_int=int(data_chr_tmp.encode("hex"),16)
            if(data_tmp_int==0x68):

                list_tmp.append(data_tmp_int)
                # 找6位地址，和68H，控制码
                data_str_tmp=self.serial_port.read(8)
                if(len(data_str_tmp)==8):
                    data_tmp_int = int(data_str_tmp[6].encode("hex"), 16)
                    if (data_tmp_int == 0x68):
                        for i in range(8):
                            list_tmp.append(int(data_str_tmp[i].encode("hex"), 16))
                        # 数据域长度
                        data_chr_tmp = self.serial_port.read(1)
                        if (len(data_chr_tmp)):
                            data_tmp_int = int(data_chr_tmp.encode("hex"), 16)
                            list_tmp.append(data_tmp_int)

                            # 数据域
                            data_str_tmp=self.serial_port.read(data_tmp_int)
                            if(data_tmp_int==len(data_str_tmp)):
                                for i in range(data_tmp_int):
                                    list_tmp.append(int(data_str_tmp[i].encode("hex"), 16))
                                #校验码,结尾
                                data_str_tmp = self.serial_port.read(2)
                                if (2 == len(data_str_tmp)):
                                    for i in range(2):
                                        list_tmp.append(int(data_str_tmp[i].encode("hex"), 16))
                                    return list_tmp
            else:
                pass
        del(list_tmp)
        list_tmp=[]
        return list_tmp
    def serial_data_read_all(self):
        list_tmp = []
        data_str_tmp=self.serial_port.readall()
        if(len(data_str_tmp)):
            for i in range(len(data_str_tmp)):
                list_tmp.append(int(data_str_tmp[i].encode("hex"), 16))
        self.serial_port.flushInput()
        return list_tmp

    def serial_data_write(self,data):
        self.serial_port.write(data)
        self.serial_port.flush()

if __name__ == '__main__':
    b = dianbiao_logic.tree_four_meter("123456789012",16, {})
    b.calculate_powers(60)
    a = serial_get_all_port()
    print(a)
    while 1:
        serial_tmp = serial_one_port_object("COM33", 2400)
        if (serial_tmp.check_serial_port() != None):
            try:
                while 1:
                    list_tmp = serial_tmp.serial_data_read_all()
                    if (len(list_tmp)):
                        list_tmp = connect_protocol_645().connect_data_check(list_tmp)#得到一包数据
                        if (len(list_tmp)):
                            address_tmp=int(connect_protocol_645().connect_data_get_address(list_tmp))#返回一个16进制的字符串来表示地址，被int后的值
                            diabbiao_object = b
                            if(diabbiao_object!=None):
                                list_tmp = connect_protocol_645().connect_data_analyze(list_tmp, diabbiao_object)#分析数据
                                if (serial_tmp != None):
                                    list_tmp = serial_tmp.hextostr(list_tmp)
                                else:
                                    break

                                if (len(list_tmp)):
                                    if (serial_tmp != None):
                                        serial_tmp.serial_data_write(list_tmp)
                                    else:
                                        break
            except:
                del (serial_tmp)
        else:
            pass

